import URL from '@/config/url'
import store from '@/store/modules/index'

const utils = {
	
	// 发送请求
	uniRequest({ url, data, method = 'POST',header} = {}) {
		// #ifdef MP-WEIXIN
		   let X_FROM  = 'miniprogram'
		// #endif
		//  #ifdef APP-PLUS 
		   let  X_FROM = '';
		   if(uni.getSystemInfoSync().platform == 'ios'){
			X_FROM  = 'ios'
		   }else if(uni.getSystemInfoSync().platform === 'android') {
			X_FROM  = 'android'
		   }
		//  #endif 
		//  #ifdef H5 
		   let X_FROM  = 'h5'
		//  #endif
		let access_token = uni.getStorageSync('token') || ''
		let user_id = uni.getStorageSync('userId') || ''
		let market_id = uni.getStorageSync('Marketid') || 1
		
		if(!user_id){
			access_token = store.state.token || ''
			user_id = store.state.userId || ''
		}
		let headers = {
			'access-token' :access_token,
			'user-id' : user_id,
			X_FROM:X_FROM,
			'market-id': market_id
		}
		let loginshow = false
		return new Promise((resolve, reject) => {
			uni.request({ url, method, data,header: headers,
				success(res) {
					resolve(res.data)
					if(res.data.code == '-5' || res.data.code == '-3'){
						var t = this;
						if(loginshow == false){
							loginshow = true
							uni.showModal({
							    title: "提示！",
							    content: "请先登录！",
							    success: function(s) {
							        if (s.confirm) {
									   loginshow = false
									   // uni.clearStorageSync()
									   // uni.clearStorage()
							           uni.navigateTo({
							           	url: '/pages_login/pages/login/login/index',
							           });
							        }else if (res.cancel) {
									      loginshow = false
									}
							    }
							});
						}
						
					}
				},
				fail(err) {
					reject(err)
				}
			})
		})
	},

	// 登录
	login({ success } = {}) {
		uni.login({
			success: (res) => {
				if (res.code) {
					if (typeof success === 'function') success(res)
				}
				else {
					this.hideLoading()
					this.showErr()
				}
			},
			fail: () => {
				this.hideLoading()
				this.showErr()
			}
		})
	},
	// 贮存当前页面
	getUrl() {
	    var pages = getCurrentPages() //获取加载的页面  
	    var currentPage = pages[pages.length - 1] //获取当前页面的对象  
	    var url = currentPage.route //当前页面url  
	    uni.setStorageSync('Router', `${url}`)  
	    var options = currentPage.options //如果要获取url中所带的参数可以查看options  
	    console.info(url);
	    console.info(options);
	    //参数多时通过&拼接url的参数  
	    if(options){
	        var urlWithArgs = url + '?'  
	        for (var key in options) {  
	        var value = options[key]  
	        urlWithArgs += key + '=' + value + '&'  
	        } 
		 urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)  
		        // wx.setStorageSync('Url', `/${urlWithArgs}`)  
		        uni.setStorageSync('Router', `${urlWithArgs}`) 
				console.info(urlWithArgs);
		    }
		}, 
	gitsetting(){
		let tmplIds = ['s6Ulqf1NM07FYQ6kuvZVkX-l_jRy18DYaY9oTnuqSk0','dnCmW83lNEl_zH8HlUWboOcqnHn9BRWzJ57nmzl1b4U','MeFxMOCulx_ub5h7CJ18WpvATcpu9NkcxN-hT93GsWA']
		// 这里是获取下发权限地方，根据官方文档，可以根据  wx.getSetting() 的 withSubscriptions   这个参数获取用户是否打开订阅消息总开关。后面我们需要获取用户是否同意总是同意消息推送。所以这里要给它设置为true 。
		wx.getSetting({
		      withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
		      success: function(res){   
		        // 调起授权界面弹窗
		        if (res.subscriptionsSetting.mainSwitch) {  // 用户打开了订阅消息总开关
		          if (res.subscriptionsSetting.itemSettings != null) {   // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
		            let moIdState = res.subscriptionsSetting.itemSettings[tmplIds];  // 用户同意的消息模板id
		            if(moIdState === 'accept'){   
		              console.log('接受了消息推送');
		            }else if(moIdState === 'reject'){
		              console.log("拒绝消息推送");
		            }else if(moIdState === 'ban'){
		              console.log("已被后台封禁");
		            }
		          }else {
		          	// 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
					   wx.requestSubscribeMessage({   // 调起消息订阅界面
						 tmplIds: tmplIds,
						 success (res) { 
						   console.log('订阅消息 成功 ');
						   console.log(res);
						 },
						 fail (er){
						   console.log("订阅消息 失败 ");
						   console.log(er);
						 }
					   })   
		          }
		
		        }else {
		          console.log('订阅消息未开启')
		        }      
		      },
		      fail: function(error){
		        console.log(error);
		      },
		    })
	},
	// 错误提示
	showErr({ title = '网络异常，请稍后再试', icon = 'none', duration = 1500, mask = false } = {}) {
		uni.showToast({ title, icon, duration, mask })
	},
	
	// 加载提示
	showLoading({ title = '加载中...', mask = true } = {}) {
		uni.showLoading({ title, mask })
	},
	
	// 隐藏加载提示
	hideLoading() {
		uni.hideLoading()
	},
	
	// 时间戳转化为几天前，几小时前，几分钟前
	getDateDiff(dateTimeStamp){
	  var result;
	    var minute = 1000 * 60;
	    var hour = minute * 60;
	    var day = hour * 24;
	    var halfamonth = day * 15;
	    var month = day * 30;
	    var now = new Date().getTime();
	    var diffValue = now - dateTimeStamp;
	    if(diffValue < 0){
	    return;
	  }
	    var monthC =diffValue/month;
	    var weekC =diffValue/(7*day);
	    var dayC =diffValue/day;
	    var hourC =diffValue/hour;
	    var minC =diffValue/minute;
	    if(monthC>=1){
	    if(monthC<=12)
	          result="" + parseInt(monthC) + "月前";
	    else{
	      result="" + parseInt(monthC/12) + "年前";
	    }
	    }
	    else if(weekC>=1){
	        result="" + parseInt(weekC) + "周前";
	    }
	    else if(dayC>=1){
	        result=""+ parseInt(dayC) +"天前";
	    }
	    else if(hourC>=1){
	        result=""+ parseInt(hourC) +"小时前";
	    }
	    else if(minC>=1){
	        result=""+ parseInt(minC) +"分钟前";
	    }else{
			result="刚刚";
	  }
	    return result;
    },
	
	// 获取周几
	getweekday(date){
		let weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
		let week = weekArray[new Date(date).getDay()];//注意此处必须是先new一个Date
		return week;
	},
	
	// 获取格式化日期
	getFormatDate(t, fmt = 'yyyy-MM-dd') {
		let time = t instanceof Date ? t : new Date(typeof t === 'string' ? t.replace(/\-/g, "/") : t)
		if (time instanceof Date && !isNaN(time.getTime())) {
			let o = {
				'M+': time.getMonth() + 1,
				'd+': time.getDate(),
				'h+': time.getHours(),
				'm+': time.getMinutes(),
				's+': time.getSeconds()
			}
			if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length))
			for (var k in o) {
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
			}
			return fmt
		}
		else {
			return 'NaN'
		}
	},
	// 获取两个时间戳之间的天数
		getDaysAndHours(blockingTime,dateNow){
			if(!dateNow){
				dateNow = new Date().getTime()
			}
			// let dateNow = new Date();  // 获取当前时间
			
			let timeDiff = blockingTime - dateNow;  // 时间差的毫秒数
			// timeDiff = 时间戳差值
			
			let days = Math.floor(timeDiff / (24 * 3600 * 1000)); // 计算出天数
			let leavel1 = timeDiff % (24 * 3600 * 1000); // 计算天数后剩余的时间
			let hours = Math.floor(leavel1 / (3600 * 1000)); // 计算天数后剩余的小时数
			// let leavel2 = timeDiff % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
			// let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
			
			// return days+'天'+hours+'小时';
			return days;
		},
	
	// js加法
	accAdd(arg1, arg2) {
		let r1, r2, m
		try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
		try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
		m = Math.pow(10, Math.max(r1, r2))
		return (this.accMul(arg1, m) + this.accMul(arg2, m)) / m;   
	},

	// js减法
	accSub(arg1, arg2) {
		let r1, r2, m
		try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
		try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
		m = Math.pow(10, Math.max(r1, r2));
		return (this.accMul(arg1, m) - this.accMul(arg2, m)) / m;  
	},

	// js乘法
	accMul(arg1, arg2) {
		let m = 0, s1 = arg1.toString(), s2 = arg2.toString()
		try { m += s1.split(".")[1].length } catch (e) { }
		try { m += s2.split(".")[1].length } catch (e) { }
		return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
	},

	// js除法
	accDiv(arg1, arg2) {    
		let t1 = 0, t2 = 0, r1, r2 
		try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
		try { t2 = arg2.toString().split(".")[1].length } catch (e) { }   
		r1 = Number(arg1.toString().replace(".", ""))    
		r2 = Number(arg2.toString().replace(".", ""))    
		return (r1 / r2) * Math.pow(10, t2 - t1)  
	},
}




export default utils
